//
//  CreateBedViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 05/04/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "CreateBedViewController.h"
#import "Plot+CRUD.h"
#import "AppDelegate.h"
#import "Bed+CRUD.h"

@interface CreateBedViewController()
@property (nonatomic, strong) NSManagedObjectContext *context;
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@end

@implementation CreateBedViewController
@synthesize dimensionsText = _dimensionsText;
@synthesize adjustDimensionsText = _adjustDimensionsText;
@synthesize xLabel = _xLabel;
@synthesize dimensionsLabel = _dimensionsLabel;

@synthesize bedNameTextField = _bedNameTextField;
@synthesize plotNameLabel = _plotNameLabel;
@synthesize size1Label = _size1Label;
@synthesize size2Label = _size2Label;
@synthesize size1Stepper = _size1Stepper;
@synthesize size2Stepper = _size2Stepper;
@synthesize tempPlot = _tempPlot;
@synthesize currentPlot = _currentPlot;
@synthesize context = _context;
@synthesize tap = _tap;

/*Configure the stepper object for the bed dimensions*/
- (void)setupDimensionStepper:(UIStepper *)stepper
{
    stepper.minimumValue = 1;
    stepper.maximumValue = 1000;
    stepper.stepValue = 1;
    stepper.wraps = NO;
    stepper.autorepeat = YES;
    stepper.continuous = YES;
}

/*Set the fonts on each screen label*/
-(void)setFonts
{
    self.plotNameLabel.font = [UIFont fontWithName:@"Sketch Rockwell" size:24];
    self.plotNameLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    
    self.xLabel.font = [UIFont fontWithName:@"Sketch Rockwell" size:28];
    self.xLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    
    self.size1Label.font = [UIFont fontWithName:@"Sketch Rockwell" size:32];
    self.size1Label.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    
    self.size2Label.font = [UIFont fontWithName:@"Sketch Rockwell" size:32];
    self.size2Label.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    
    
    self.dimensionsText.font = [UIFont fontWithName:@"MV Boli" size:16];
    self.dimensionsText.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    
    self.adjustDimensionsText.font = [UIFont fontWithName:@"MV Boli" size:16];
    self.adjustDimensionsText.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.context = [(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext]; 
    
    //Set the background image
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"paper.png"]];
    tempImageView.frame = self.view.frame;
    
    //Configure the first stepper
    [self setupDimensionStepper:self.size1Stepper];
    self.size1Label.text = [NSString stringWithFormat:@"%.f", self.size1Stepper.value];
    
    //Configure the second stepper
    [self setupDimensionStepper:self.size2Stepper];
    self.size2Label.text = [NSString stringWithFormat:@"%.f", self.size2Stepper.value];
    
    //Configure the rightBarButtonItem based on the number of beds to create and the stage in the creation process
    if(self.currentPlot != nil){
        self.navigationItem.rightBarButtonItem.title = @"Save";
    }else{        
        if(self.tempPlot.numberOfBedsToAdd == ([self.tempPlot.beds count] +1)){
            self.navigationItem.rightBarButtonItem.title = @"Save";
        }else{
            self.navigationItem.rightBarButtonItem.title = @"Next";
        }
    }
    
    //Set the dimensions text based on the user's unit of measurement preference
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    if([prefs boolForKey:@"metric"]){
        self.dimensionsLabel.text = [self.dimensionsLabel.text stringByAppendingString:@" Meters"];
    }else {
        self.dimensionsLabel.text = [self.dimensionsLabel.text stringByAppendingString:@" Feet"];
    }
    
    [self setFonts];
}

-(void)viewWillAppear:(BOOL)animated
{
    if(self.currentPlot != nil){
        self.plotNameLabel.text = self.currentPlot.name;
    }else{
        self.plotNameLabel.text = self.tempPlot.name;
    }
}

- (void)viewDidUnload
{
    [self setPlotNameLabel:nil];
    [self setBedNameTextField:nil];
    [self setSize1Label:nil];
    [self setSize2Label:nil];
    [self setSize1Stepper:nil];
    [self setSize2Stepper:nil];
    [self setDimensionsText:nil];
    [self setAdjustDimensionsText:nil];
    [self setXLabel:nil];
    [self setDimensionsLabel:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)size1StepperValueChanged:(UIStepper *)sender 
{
    double stepperValue = sender.value;
    if(stepperValue > 0){
        self.size1Label.text = [NSString stringWithFormat:@"%.f", stepperValue];
    }
}

- (IBAction)size2StepperValueChanged:(UIStepper *)sender 
{
    double stepperValue = sender.value;
    if(stepperValue > 0){
        self.size2Label.text = [NSString stringWithFormat:@"%.f", self.size2Stepper.value]; 
    }
    
}

/*Add a temporary bed object to the temporary plot object.
 A temp object is used to hold the plot and bed info until the end of the creation process when we create
 the real plot and bed*/
- (void)addBedToTempPlot
{
    TempBed *bed = [[TempBed alloc] init];
    bed.name = self.bedNameTextField.text;
    
    //Set up a formatter to convert the string values of the dimensions to integers
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    bed.size1 = [formatter numberFromString:self.size1Label.text];
    bed.size2 = [formatter numberFromString:self.size2Label.text];
    [self.tempPlot addBedsObject:bed];
}


- (IBAction)rightBarButtonItemPressed:(UIBarButtonItem *)sender 
{
    if(self.currentPlot != nil){
        [self.presentingViewController dismissModalViewControllerAnimated:YES];
    }else{       
        //If we have created all the beds then take the temp plot and bed, then create the real objects
        if(self.tempPlot.numberOfBedsToAdd == ([self.tempPlot.beds count] +1)){
            //Add the current Bed we are on
            [self addBedToTempPlot];
            //Insert Plot
            Plot *createdPlot = [Plot createPlotFromTempPlot:self.tempPlot WithContext:self.context];
            //Insert Beds
            for (TempBed *bed in self.tempPlot.beds) {
                Bed *createdBed = [Bed createBedFromTempBed:bed withContext:self.context];
                if (createdBed != nil) {
                    //Add bed to plot
                    [createdPlot addBedsObject:createdBed];
                    //Set the plot on the new bed
                    createdBed.plot = createdPlot;
                }
            }
           
            [self.presentingViewController dismissModalViewControllerAnimated:YES];
            //Else we just instantiate a new CreateBedViewController and navigate to it
        }else{
            [self addBedToTempPlot];
            CreateBedViewController *createBedVC = [[UIStoryboard storyboardWithName:@"PlotStoryboard" bundle:NULL] instantiateViewControllerWithIdentifier:@"AddBedView"];
            //Pass the temporary plot on to the new view controller.
            createBedVC.tempPlot = self.tempPlot;
            [self.navigationController pushViewController:createBedVC animated:YES];
        }
    }
}

- (IBAction)nameFieldTouched:(id)sender 
{
    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:self.tap];
}

-(void)dismissKeyboard {
    [self.bedNameTextField resignFirstResponder];
    [self.view removeGestureRecognizer:self.tap];
}

- (IBAction)cancelButtonPressed:(id)sender 
{
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}
@end
